import json
from collections import defaultdict


def count_matches(json_data):
    # 初始化计数器
    total = 0
    match_count = 0
    # 用于统计每个类别的匹配情况
    category_matches = defaultdict(int)
    category_total = defaultdict(int)

    for item in json_data:
        total += 1
        # 去除 label 中的换行符（因为数据中 label 有 "\n"）
        predict = item["predict"].strip()
        label = item["label"].strip()

        # 统计每个类别的总出现次数（基于 label）
        category_total[label] += 1

        # 检查是否匹配
        if predict == label:
            match_count += 1
            category_matches[label] += 1

    return {
        "总样本数": total,
        "匹配样本数": match_count,
        "匹配率": match_count / total if total > 0 else 0,
        "各类别匹配数": dict(category_matches),
        "各类别总样本数": dict(category_total)
    }


if __name__ == "__main__":
    # 假设你的 JSON 数据保存在文件中，每行一个 JSON 对象（JSON Lines 格式）
    file_path = "/media/dengyunfei/6T/code/llamafactory/saves/Qwen2.5-VL-7B-Instruct/lora/eval_2025-08-29-09-16-43/generated_predictions.jsonl"

    # 读取 JSON 数据
    json_data = []
    with open(file_path, "r", encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if line:
                json_data.append(json.loads(line))

    # 统计匹配情况
    result = count_matches(json_data)

    # 打印结果
    print(f"总样本数: {result['总样本数']}")
    print(f"predict 与 label 匹配的样本数: {result['匹配样本数']}")
    print(f"匹配率: {result['匹配率']:.2%}")
    print("\n各类别匹配详情:")
    for category in ["上升趋势", "下降趋势", "横盘趋势"]:
        matches = result["各类别匹配数"].get(category, 0)
        total = result["各类别总样本数"].get(category, 0)
        rate = matches / total if total > 0 else 0
        print(f"{category}: 总样本 {total} 个，匹配 {matches} 个，匹配率 {rate:.2%}")

#  pip install opencv-contrib-python numpy==1.26.4